package com.player.thirdGroup.controller;

import com.player.thirdGroup.entity.Dept;
import com.player.thirdGroup.entity.Message;
import com.player.thirdGroup.entity.Player;
import com.player.thirdGroup.entity.User;
import com.player.thirdGroup.service.PlayerService;
import com.player.thirdGroup.util.LoadUtil;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author VULCAN
 * @create 2019-12-28 7:50
 * @desc 运动员44444444444444444444
 **/
@Controller
public class PlayerControlller {
    @Autowired
    private PlayerService playerService;
    //分页模糊列表
    @PostMapping("playerlist")
    @ResponseBody
    public Page<Player> findAll(@RequestBody Player player, int page, int size){

        return playerService.findAll(player, page, size);
    }
    //列表
    @GetMapping("playerunderlist")
    @ResponseBody
    public List<Player> playerunderlist(){
        List<Player> all = playerService.findAll();
        return all;
    }
    //列表 中转
    @GetMapping("personnel")
    public String personnel(){
        return "personnel";
    }
    //列表 中转
    @GetMapping("playerunder")
    public String playerunder(Model model){
        String countpass =  playerService.countpass();
        String countnopass = playerService.countnopass();
        String countunder = playerService.countunder();
        model.addAttribute("countunder",countunder);
        model.addAttribute("countnopass",countnopass);
        model.addAttribute("countpass",countpass);
        return "playerunder";
    }
    //审核通过
    @GetMapping("playerunderpass")
    @ResponseBody
    public Player playerunderpass(String id) throws UnknownHostException {
        return playerService.deptunderpass(id);
    }
    //审核不通过
    @GetMapping("playerundernopass")
    @ResponseBody
    public Player playerundernopass(String id) throws UnknownHostException {
        return playerService.deptundernopass(id);
    }
    //批量审核通过
    @RequestMapping(value = "playerbulkpass",method = RequestMethod.GET)
    @ResponseBody
    public String playerbulkpass(@RequestParam Long[] ids) throws UnknownHostException {
        return playerService.bulkpass(ids);
    }
    //批量审核不通过
    @RequestMapping(value = "playerbulknopass",method = RequestMethod.GET)
    @ResponseBody
    public String playerbulknopass(@RequestParam Long[] ids) throws UnknownHostException {
        return playerService.bulknopass(ids);
    }
    //改变状态
    @RequestMapping(value = "playerupdatestatus",method = RequestMethod.GET)
    @ResponseBody
    public List<Player> playerupdatestatus(String status){
        return playerService.updatestatus(status);
    }

    //查看驳回原因
    @RequestMapping(value = "filedown",method = RequestMethod.POST)
    @ResponseBody
    public String reason(String id ,User user) {

        playerService.reason(id,user);

        return "驳回成功";
    }
    //批量驳回
    @RequestMapping(value = "playerfiledownids",method = RequestMethod.POST)
    @ResponseBody
    public String playerfiledownids(@RequestParam Long[] ids , User user) {
        playerService.playerreasonids(ids,user);
        return "驳回成功";
    }
    //查看驳回原因
    @RequestMapping(value = "playerlookturn",method = RequestMethod.GET)
    @ResponseBody
    public Message lookturn(String id) {
        return playerService.lookturn(id);
    }
    /**
     * @liuwen
     * 跳转运动员注册页面
     * @return
     */
    @RequestMapping("/inserthtml")
    public String inserHtml(){
        return "add";
    }
    /**
     *
     * @liuwen
     *
     * 运动员注册
     * @param id
     * @param name
     * @param sex
     * @param age
     * @param birthday
     * @param height
     * @param weight
     * @param number
     * @param student
     * @param hand
     * @param location
     * @param year1
     * @param did
     * @param cdate
     * @param year2
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insert(
            @RequestParam("id") String id,
            @RequestParam("name") String name,
            @RequestParam("sex") String sex,
            @RequestParam("age") int age,
            @RequestParam("birthday") String birthday,
            @RequestParam("height") String height,
            @RequestParam("weight") String weight,
            @RequestParam("number") String number,
            @RequestParam("student") String student,
            @RequestParam("hand") String hand,
            @RequestParam("location") String location,
            @RequestParam("year1") String year1,
            @RequestParam("did") String did,
            @RequestParam("cdate") String cdate,
            @RequestParam("year2") String year2 ,
            MultipartFile file1,
            MultipartFile file2,
            MultipartFile file3,
            MultipartFile file4) throws ParseException {
        LoadUtil.ScPhoto(file1);
        LoadUtil.ScPhoto(file2);
        LoadUtil.ScPhoto(file3);
        LoadUtil.ScPhoto(file4);
        final String frout = "/img/"+file1.getOriginalFilename();
        final String side = "/img/"+file2.getOriginalFilename();
        final String book = "/img/"+file3.getOriginalFilename();
        final String img =  "/img/"+file4.getOriginalFilename();
        //获取到UUID
        String s = UUID.randomUUID().toString();
        //创建实体类对象player
        Player player = new Player();
        player.setId(s);
        player.setName(name);
        player.setSex(sex);
        player.setAge(age);
        //获取到的时间只能是String类型的时间，只能将String转换成Data
        SimpleDateFormat datbirthdayeFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = datbirthdayeFormat.parse(birthday);
        player.setBirthday(parse);
        player.setHeight(height);
        player.setWeight(weight);
        player.setNumber(number);
        player.setStudent(student);
        player.setHand(hand);

        player.setLocation(location);
        SimpleDateFormat datbirthdayeFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        Date parse1 = datbirthdayeFormat1.parse(year1);
        SimpleDateFormat datbirthdayeFormat4 = new SimpleDateFormat("yyyy-MM-dd");
        Date parse3 = datbirthdayeFormat4.parse(year2);
        player.setYear1(parse1);
        player.setYear2(parse3);
        player.setFrout(frout);
        player.setSide(side);
        player.setBook(book);
        Dept d=new Dept();
        d.setId(did);
        player.setDept(d);
        SimpleDateFormat datbirthdayeFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        Date parse2 = datbirthdayeFormat2.parse(cdate);
        player.setCdate(parse2);
        player.setImg(img);
        playerService.insert(player);

        return  "playerlist";
    }

    @RequestMapping("listhtml")
    public String getList(){
        return "playerlist";
    }

    @RequestMapping("findAll")
    @ResponseBody
    public List<Player> FindAll(HttpServletResponse response){

        System.out.println("findAll");
        List<Player> all = playerService.findAll();
        return all;
    }
    //年度确认
    @RequestMapping(value = "Annual",method = RequestMethod.GET)
    @ResponseBody
    public List<Player> Annual() {
        return playerService.Annual();
    }
    //再次注册
    @RequestMapping(value = "beginregister",method = RequestMethod.GET)
    @ResponseBody
    public List<Player> beginregister() {
        return playerService.beginregister();
    }
    //首次注册
    @RequestMapping(value = "register",method = RequestMethod.GET)
    @ResponseBody
    public List<Player> register() {
        return playerService.register();
    }

    //导出
    @RequestMapping(value = "playerExcel",method = RequestMethod.GET)
    @ResponseBody
    public void playerExcel(HttpServletRequest req, HttpServletResponse resp, String type) throws IOException {
        //列名
        List<String> headers = Arrays.asList("ID", "姓名","性别","年龄","出生日期",
                "身高",
                "体重",
                "证件号码",
                "学号",
                "左右手",
                "场上位置",
                "注册单位",
                "协议年限",
                "证件正面",
                "证件反面",
                "户口本");
        List<Map<String, String>> exportDatas = new ArrayList<Map<String, String>>();
        List<Player> orderProductAttrList = playerService.findAll();

        //将查询结果，存放进列值
        for (Player player : orderProductAttrList) {
            Map<String,String> map=new HashMap<>();
            map.put("ID", player.getId());
            map.put("姓名", player.getName());
            map.put("性别", player.getSex());
            map.put("年龄", player.getAge()+"");
            map.put("出生日期", player.getBirthday()+"");
            map.put("身高", player.getHeight());
            map.put("体重", player.getWeight());
            map.put("证件号码", player.getNumber());
            map.put("学号", player.getStudent());
            map.put("左右手", player.getHand());
            map.put("场上位置", player.getLocation());
            map.put("注册单位", player.getDept().getName());
            map.put("协议年限", player.getFrout());
            map.put("证件正面", player.getYear1()+"");
            map.put("证件反面", player.getYear2()+"");
            map.put("户口本", player.getBook());
            exportDatas.add(map);
        }
        //导出
        exportExcel(req,resp,headers,exportDatas);
    }

    public void exportExcel(HttpServletRequest req, HttpServletResponse resp, List<String> headers, List<Map<String, String>> exportDatas) throws IOException {
        // 创建一个工作薄
        SXSSFWorkbook wb = new SXSSFWorkbook();
        //创建sheet
        Sheet sh = wb.createSheet("运动员信息");
        //设置表头字体
        Font headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setColor(HSSFColor.WHITE.index);
        headFont.setFontHeightInPoints((short) 10);// 字体大小
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗

        // 设置表头样式
        CellStyle headStyle = wb.createCellStyle();
        headStyle.setFont(headFont);
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        headStyle.setLocked(true);
        headStyle.setWrapText(true);// 自动换行
        headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(HSSFColor.GREEN.index);

        // 设置普通单元格字体
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);

        // 设置普通单元格样式
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中
        style.setWrapText(true);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft((short) 1);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight((short) 1);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体
        style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色．
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色．

        //设置单位格样式为文本
        DataFormat dataFormat = wb.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));

        /**
         * 设置列名
         */
        Row sheetRow = sh.createRow(0);
        Cell cell = null;
        for (int i = 0; i < headers.size(); i++) {
            cell = sheetRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(headStyle);
        }

        /**
         * 设置列值
         */
        int rows = 1;
        for (Map<String, String> data : exportDatas) {
            Row row = sh.createRow(rows++);
            int initCellNo = 0;
            int titleSize = headers.size();
            for (int i = 0; i < titleSize; i++) {
                String key = headers.get(i);
                Object object = data.get(key);
                if (object == null) {
                    row.createCell(initCellNo).setCellValue("");
                } else {
                    row.createCell(initCellNo).setCellValue(String.valueOf(object));
                }
                initCellNo++;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "运动员信息" + sdf.format(new Date()) + ".xlsx";
        resp.setContentType("application/octet-stream;charset=utf-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }

}
